package com.lute.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.oauth2.common.json.JSONArray;
import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.json.CalendarEntriesJSON;
import com.lute.model.Client;
import com.lute.model.Employee;
import com.lute.model.EmployeeEntry;
import com.lute.model.EmployeeProfile;
import com.lute.model.User;
import com.lute.utils.ServerErrorResponse;

@Controller
public class CalculateCreativeHoursServlet {
	
	
	@RequestMapping(value="/calculateCreativeHours",method = RequestMethod.POST,headers = "Content-type=application/json")
	public @ResponseBody String calculateCreativeHours(@RequestBody String calendarEntriesDataJSON,HttpServletRequest request) throws JSONException {
		String result = "";
		JSONArray calendarEntries;
		String userId;
		JSONObject jsonReq;
		JSONObject jsonRes = new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		try {
			jsonReq = new JSONObject(calendarEntriesDataJSON);
			calendarEntries = jsonReq.getJSONArray("calendarEntries");
			userId = jsonReq.getString("userId");
		} catch(JSONException e) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			System.out.println("1");
			e.printStackTrace();
			return result;
		}
		
		if(jsonReq.isNull("calendarEntries") && (jsonReq.isNull("userId"))) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			System.out.println("2");
			return result;
		}
		
		int workedHours = 0;
		int numberOfDays = 0;
		
		for(int i=0; i<calendarEntries.length(); i++) {
			String hoursStr =  calendarEntries.getJSONObject(i).getString("hours");
			if(Integer.parseInt(hoursStr) < 0) {
				jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
				result = jsonRes.toString();
				System.out.println("3");
				return result;
			}
			String companyCategory =  calendarEntries.getJSONObject(i).getString("companyCategory");
			if(((companyCategory.equals("workClient")) || (companyCategory.equals("workCompany"))) ) {
				int hours = Integer.parseInt(hoursStr);
				workedHours += hours;
				numberOfDays++;
			}
		}
		
		if((numberOfDays == 0) || (workedHours == 0)) {
			jsonRes.put("result", ServerErrorResponse.NOTHING_TO_GENERATE.toString());
			result = jsonRes.toString();
			return result;
		}
		
		String role = (String)session.getAttribute("role");
		Integer employeeId = (Integer)session.getAttribute("sessionUserId");
		
		ArrayList<CalendarEntriesJSON> calendarEntriesJSON = new ArrayList<CalendarEntriesJSON>();
		
		try {
			
			EmployeeProfile employeeProfile = null;
			
			if(role.equals("clientAdmin")) {
				if(jsonReq.isNull("userId")) {
					jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
					result = jsonRes.toString();
					System.out.println("4");
					return result;
				}
				User user = User.getUserFromDB("id_user", Integer.parseInt(userId));
				employeeProfile = EmployeeProfile.getEmployeeProfileByEmployeeIdFromDB(user.getRole().getName(), Integer.parseInt(userId));
			} else {
				employeeProfile = EmployeeProfile.getEmployeeProfileByEmployeeIdFromDB(role, employeeId);
			}
			
			if(employeeProfile == null) {
				jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
				result = jsonRes.toString();
				System.out.println("5");
				return result;
			}
			
			/* check if employee has creative hours*/
			if(employeeProfile.getPositions().getCreativity_percentage() == null) {
				jsonRes.put("result", ServerErrorResponse.EMPLOYEE_CANNOT_HAVE_CREATIVE_HOURS.toString());
				result = jsonRes.toString();
				return result;
			}
			
			calendarEntries = User.calculateCreativeHours(employeeProfile, calendarEntries, workedHours, numberOfDays);
	
			CalendarEntriesJSON calendarJSON = null;
			for(int i =0; i < calendarEntries.length(); i++ ) {
				calendarJSON = new CalendarEntriesJSON();
				calendarJSON.setCompanyCategory(calendarEntries.getJSONObject(i).getString("companyCategory"));
				calendarJSON.setCreativeHours(calendarEntries.getJSONObject(i).getString("creativeHours"));
				calendarJSON.setDate(calendarEntries.getJSONObject(i).getString("date"));
				calendarJSON.setHours(calendarEntries.getJSONObject(i).getString("hours"));
				calendarEntriesJSON.add(calendarJSON);
			}
		} catch(NullPointerException npe) {
			jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
			result = jsonRes.toString();
			npe.printStackTrace();
			return result;
		}
		jsonRes.put("result","OK");
		jsonRes.put("calendarEntries",calendarEntriesJSON);
		result = jsonRes.toString();
		return result;
	}
}
